<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2016-10-22
 * Time: 10:27
 */

namespace app\src\payment\action;


use app\src\base\action\BaseAction;
use app\src\payment\helper\PayCodeHelper;
use app\src\payment\logic\PaymentLogic;
use app\src\profit\enum\ProfitEnum;
use app\src\seller\emnu\SellerOrderStatusEmnu;
use app\src\seller\logic\SellerLogic;
use app\src\seller\logic\SellerOrderLogic;
use think\Db;

class PaymentAction extends BaseAction{

    /*
     * 生成支付订单-回调用
     */
    public function addPayment($type,$total_fee,$order_code,$trade_code,$pay_status){
        $seller_order=(new SellerOrderLogic())->getInfo(['order_code'=>$order_code]);
        if($seller_order['status']){
            if(!empty($seller_order['info'])){
                $order_code=$seller_order['info']['order_code'];
                if($seller_order['info']['order_status']!==SellerOrderStatusEmnu::UNPAY) return $this->error('订单已处理');
            }else{
                return $this->error('找不到订单');
            }
        }else{
            return $this->error('查询订单出错');
        }

        $is_repeat=(new PaymentLogic())->getInfo(['order_code'=>$order_code]);
        if(!empty($is_repeat['info']))return $this->error(['order_id'=>$seller_order['info']['id']]);

        $data = [
            'type' => $type,
            'total_fee'=>$total_fee,
            'order_code' => $order_code,
            'pay_code' => '',
            'pay_status' => $pay_status,
            'trade_code' => $trade_code,
            'create_time' => NOW_TIME,
            'status' => 0,
        ];

        $result = (new PaymentLogic())->add($data);
        if($result['status']){
            if($pay_status==1){
                //如果是支付成功，则生成支付码，并写回seller—order
                $id = $result['info'];
                if($type==1) $pay_type=PayCodeHelper::ALPAY_ORDER;
                if($type==2) $pay_type=PayCodeHelper::WXPAY_ORDER;
                $pay_code=PayCodeHelper::create($pay_type, $id);
                (new PaymentLogic())->saveByID($id, ['pay_code' => $pay_code]);
                $seller_order_save = (new SellerOrderLogic())->save(['order_code'=>$order_code],['pay_code'=>$pay_code,'order_status'=>'1','pay_time'=>NOW_TIME]);

                if(!$seller_order_save['status'])return $this->error($seller_order_save['info']);
            }
            $profit_amount = $seller_order['info']['amount']-$seller_order['info']['no_discount'];
            return $this->success(['order_id'=>$seller_order['info']['id'],'profit_amount'=>$profit_amount]);
        }else{
            return $this->error($result['info']);
        }
    }




}